package com.xiaojiezhu.netty.base.demo.receive;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

/**
 * @Author 朱小杰
 * 时间 2017-07-13 .23:24
 * 说明 接收消息，读取消息
 */
public class ReceiveServiceHandler extends ChannelInboundHandlerAdapter {
    /**
     * 接收到消息 的时候
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println(in.toString(CharsetUtil.US_ASCII));
        in.release(); //释放
    }

    /**
     * 第一种方法读取
     * @param msg
     */
    private void read1(Object msg) {
        ByteBuf in = (ByteBuf) msg;
        try{
            while (in.isReadable()){
                System.out.println((char)in.readByte());
                System.out.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg); //释放
        }
    }

    /**
     * 发生异常的时候
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
